const {
    parseRating
} = require('./toolkit');

function update({ stocks, updateAt, source }) {
    let codes = Object.keys(stocks);
    let ratings = codes.map(c => {
        let { level, action } = parseRating(stocks[c]);
        return {
            code: c,
            type: source,
            level, action,
            date: updateAt
        }
    });
    for (let r of ratings) {
        tryUpdateRating(r);
    }
}

function updateRating(r, stock) {
    return Ratings().findOne({
        where: {
            StockCode: r.code
        }
    }).then(rating => {
        if (rating) {
            if (rating.action == r.action && rating.level == r.level) {
                console.log(`no changes for ${r.code}...${rating.level} (${rating.action})`);
                return;
            }
            console.log(`the rating of ${r.code} has been changed...${rating.level} (${rating.action}) ===> ${r.level} (${r.action})`);
        }
        return Ratings().destroy({
            where: {
                StockCode: r.code
            }
        }).then(dr => {
            RatingHistory().create({
                level: r.level,
                action: r.action,
                type: r.type,
                date: r.date,
                StockCode: r.code
            });
            return Ratings().create({
                level: r.level,
                action: r.action,
                type: r.type,
                date: r.date,
                StockCode: r.code
            })
        })
    });
}

function tryUpdateRating(r) {
    return Stock().findOne({
        where: {
            code: r.code
        }
    }).then(stock => {
        return Stock().insertOrUpdate({
            code: r.code,
            name: r.code,
            avgRating: r.level,
            action: r.action
        }).then(stock => {
            return updateRating(r, stock);
        });
    });
}

function Stock() {
    return require('../models').db.Stock;
}

function Ratings() {
    return require('../models').db.Ratings;
}

function RatingHistory() {
    return require('../models').db.RatingHistory;
}

module.exports = {
    update
}